/**
 * @Description MyPCController.java
 * @author xu_cc [18724000100@163.com]
 * @date 创建时间：2017年12月4日 上午9:27:26
 */
package com.solution.pc.my.controller;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import sun.misc.BASE64Decoder;

import com.solution.admin.auth.entity.UserEntity;
import com.solution.admin.auth.service.UserService;
import com.solution.admin.company.service.CompanyInvoiceService;
import com.solution.admin.customer.entity.CompanyEntity;
import com.solution.admin.customer.entity.CustomerEntity;
import com.solution.admin.customer.service.CompanyService;
import com.solution.admin.customer.service.CustomerService;
import com.solution.admin.order.controller.OrderInvoiceController;
import com.solution.admin.order.service.OrderInvoiceService;
import com.solution.admin.order.service.OrderService;
import com.solution.common.constants.PublicStatus;
import com.solution.common.constants.PublicStatus.SysCode;
import com.solution.common.controller.BaseController;
import com.solution.common.entity.BaseReturn;
import com.solution.common.entity.UserPrincipal;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.string.StringUtil;
import com.solution.common.utils.upload.OssUploadFile;
import com.solution.wx.share.entity.ShareInfoEntity;
import com.solution.wx.share.service.ShareInfoService;

/**
 * PC端个人中心
 * 
 * @author xu_cc
 * @date 创建时间：2017年12月4日 上午9:28:00
 */
@RequestMapping("/pc/my")
@Controller("pcMyController")
public class MyPCController extends BaseController {

	@Autowired
	UserService userService;

	@Autowired
	CustomerService customerService;

	@Autowired
	CompanyService companyService;
	
	@Autowired
	private CompanyInvoiceService companyInvoiceService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private ShareInfoService shareInfoService;

	/**
	 * PC端个人中心
	 * 
	 * @param request
	 * @param model
	 * @return String
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年12月4日 上午9:45:55
	 */
	@RequestMapping("")
	public String toMyPcPage(HttpServletRequest request, Model model) {
		try {
			UserEntity user = userService.getUserById(getUserId());
			CompanyEntity company = companyService.getCompanyById(getCompanyId());
			model.addAttribute("user", user);
			model.addAttribute("company", company);
			model.addAttribute("customerLevel", getCustomerLevel());
			// 用户菜单列表
			model.addAttribute("menuList", null);
			model.addAttribute("userId", getUserId());
			model.addAttribute("userCode", getUserCode());
			model.addAttribute("userName", getUserName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("page", "userInfo");
		return "pc/my/my";
	}

	/**
	 * 修改公司信息
	 * 
	 * @param request
	 * @param company
	 * @return BaseReturn
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年12月6日 下午5:14:21
	 */
	@RequestMapping("/modCompany")
	@ResponseBody
	public BaseReturn modCompany(HttpServletRequest request, CompanyEntity company) {
		BaseReturn result = new BaseReturn();
		try {
			company.setId(getCompanyId());
			company.setModifier(getUserName());
			int rows = companyService.updateCompany(company);
			if (rows > 0) {
				result.setCode(SysCode.SUCCESS);
				result.setMsg("修改成功~");
			} else {
				result.setCode(SysCode.FAILED);
				result.setMsg("修改失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(SysCode.ERROR);
			result.setMsg("修改失败，请重试！");
		}
		return result;
	}

	/**
	 * 删除地址
	 * 
	 * @param request
	 * @param model
	 * @param addressId
	 * @return BaseReturn
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年11月28日 下午2:30:34
	 */
	@RequestMapping("/modHeadImg")
	@ResponseBody
	public BaseReturn modHeadImg(HttpServletRequest request, String image) {
		BaseReturn result = new BaseReturn();
		try {
			if (StringUtil.isEmpty(image)) {
				result.setCode(SysCode.ERROR);
				result.setMsg("头像失败，请重试！");
				return result;
			}
			// 获取自增序列
			Long seqId = new Date().getTime();
			// 文件命名
			String newFileName = com.solution.common.utils.DateUtils.getDate("yyyyMMddHHmmssSSS") + seqId + ".png";
			// 上传
			// 减去这些：data:image/png;base64,
			String realImage = image.substring(22);
			InputStream is = castToInputStream(realImage);
			int fileLength = is.available();
			String headImage = OssUploadFile.uploadFileToAliyun(is, newFileName, Long.parseLong(fileLength + ""));
			// 更新用户
			UserEntity user = new UserEntity();
			user.setId(getUserId());
			user.setPath(headImage);
			user.setModifier(getUserName());
			userService.updateUser(user);
			// 更新客户
			CustomerEntity customer = new CustomerEntity();
			customer.setHeadImage(headImage);
			customer.setId(getCustomerId());
			customer.setModifier(getUserName());
			customerService.updateCustomer(customer);
			result.setData(headImage);
			result.setCode(SysCode.SUCCESS);
			result.setMsg("头像保存成功~");
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(SysCode.ERROR);
			result.setMsg("头像修改失败，请重试！");
		}
		return result;
	}

	/**
	 * 本地图片转成InputStream流对象。base64编码的字符串
	 * 
	 * @param base64string
	 * @return InputStream
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年12月6日 下午4:31:11
	 */
	public static InputStream castToInputStream(String base64string) {
		ByteArrayInputStream stream = null;
		try {
			BASE64Decoder decoder = new BASE64Decoder();
			byte[] bytes1 = decoder.decodeBuffer(base64string);
			stream = new ByteArrayInputStream(bytes1);
			return stream;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 修改用户名
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年3月30日 下午4:42:49
	 */
	@RequestMapping("/modUserName")
	@ResponseBody
	public Map<String,Object> modCompany(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String userName = request.getParameter("userName");
			CustomerEntity customerEntity = new CustomerEntity();
			customerEntity.setId(getCustomerId());
			customerEntity.setUserName(userName);
			int rows = customerService.updateCustomer(customerEntity);
			if (rows > 0) {
				Subject currentUser = SecurityUtils.getSubject();
				UserPrincipal user = (UserPrincipal) currentUser.getPrincipal();
				user.setUserName(userName);
				resultMap.put(PublicStatus.RESULT_CODE, "1");
				resultMap.put(PublicStatus.RESULT_MSG, "修改成功");
			} else {
				resultMap.put(PublicStatus.RESULT_CODE, "0");
				resultMap.put(PublicStatus.RESULT_MSG, "修改失败，请重试！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "修改失败，请重试！");
		}
		return resultMap;
	}

	/**
	 * 获取我的推广码
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年5月14日 下午5:31:15
	 */
	@RequestMapping("/referralCode")
	public String toMyReferralCodePage(HttpServletRequest request) {
		try {
			CustomerEntity customer = getCustomer();
			request.setAttribute("inviationCode", customer.getInvitationCode());
			request.setAttribute("page", "referralCode");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "pc/my/referral_code";
	}

	/**
	 * 我的客户
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年5月15日 下午3:59:38
	 */
	@RequestMapping("/myCustomer")
	public String toMyCustomerPage(HttpServletRequest request){
		try {
			PageParam pageParam = getPageParam(request);
			String searchKey = request.getParameter("searchKey");
			CustomerEntity customer = getCustomer();
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("searchKey", searchKey);
			paramMap.put("parentInvitationCode", customer.getInvitationCode());
			PageBean pageBean = customerService.listCustomerPage(pageParam, paramMap);
			List<Long> customerIds = new ArrayList<Long>();
			for (Object entityObject : pageBean.getRecordList()) {
				CustomerEntity entity = (CustomerEntity)entityObject;
				customerIds.add(entity.getId());
			}
			paramMap.put("customerIds", customerIds);
			Map<Long, Map<String,Object>> orderInfoMap = orderService.listUsersCustomerOrderInfo(paramMap);
			for (Object entityObject : pageBean.getRecordList()) {
				CustomerEntity entity = (CustomerEntity)entityObject;
				if (orderInfoMap.containsKey(entity.getId())) {
					entity.setExtraInfo(orderInfoMap.get(entity.getId()));
				}
				entity.setUserName(entity.getUserName().substring(0,1)+"**");
				entity.setMobile(entity.getMobile().replaceAll("(\\d{3})\\d{6}(\\d{2})", "$1******$2"));
			}
			request.setAttribute("page", "myCustomer");
			request.setAttribute("pageBean", pageBean);
			request.setAttribute("param", paramMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "pc/my/my_customer_list";
	}
	
	/**
	 * 我的分享页面
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年5月17日 下午4:10:44
	 */
	@RequestMapping("/myShared")
	public String toMySharePage(HttpServletRequest request){
		PageParam pageParam = getPageParam(request);
		String searchKey = request.getParameter("searchKey");
		String isSort = request.getParameter("isSort");
		String currentPage = request.getParameter("currentPage");
		if ("true".equals(isSort)) {
			pageParam.setPageNum(Integer.parseInt(currentPage));
		}
		List<String> orderByList = new ArrayList<String>();
		if (StringUtil.isNotNull(request.getParameter("likeSort"))) {
			orderByList.add("likeQuantity "+request.getParameter("likeSort"));
			request.setAttribute("likeSort", request.getParameter("likeSort"));
		}
		if (StringUtil.isNotNull(request.getParameter("commentSort"))) {
			orderByList.add("commentQuantity "+request.getParameter("commentSort"));
			request.setAttribute("commentSort", request.getParameter("commentSort"));
		}
		if (StringUtil.isNotNull(request.getParameter("favoriteSort"))) {
			orderByList.add("favoriteQuantity "+request.getParameter("favoriteSort"));
			request.setAttribute("favoriteSort", request.getParameter("favoriteSort"));
		}
		if (StringUtil.isNotNull(request.getParameter("viewSort"))) {
			orderByList.add("viewQuantity "+request.getParameter("viewSort"));
			request.setAttribute("viewSort", request.getParameter("viewSort"));
		}
		if (StringUtil.isNotNull(request.getParameter("registerSort"))) {
			orderByList.add("registerQuantity "+request.getParameter("registerSort"));
			request.setAttribute("registerSort", request.getParameter("registerSort"));
		}
		Map<String,Object> paramMap = new HashMap<String, Object>();
		paramMap.put("searchKey", searchKey);
		paramMap.put("orderByList", orderByList);
		paramMap.put("shareUserId", getCustomerId());
		try {
			PageBean pageBean = shareInfoService.listMySharePage(pageParam, paramMap);
			request.setAttribute("pageBean", pageBean);
			request.setAttribute("currentPage", pageBean.getCurrentPage());
			request.setAttribute("searchKey", searchKey);
			request.setAttribute("page", "myShared");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "pc/my/my_share_list";
	}
}
